﻿using EmoneyWeiXinBLL;
using EmoneyWeiXinCommon;
using EmoneyWeiXinEntity;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace EmoneyWeiXin.Controllers
{
    public class VipUserController : Controller
    {
        string activityUserMemKeyPreFix = "activityUserMemKey0012";
        string openId = string.Empty;
        MemcachedTools1 mmtols = new MemcachedTools1();
        public static object lockObj = new object();
        //
        // GET: /VipUser/
        WXUserEntity _currentUser;
        private WXUserEntity CurrentUser
        {
            get
            {
                if (_currentUser != null)
                {
                    return _currentUser;
                }
                else
                {
                    _currentUser = mmtols.Get<WXUserEntity>(activityUserMemKeyPreFix + openId);
                    if (_currentUser != null)
                    {
                        return _currentUser;
                    }
                    else
                    {
                        _currentUser = WXUserBLL.GetWxuserByOpenId(openId);
                        mmtols.Add(activityUserMemKeyPreFix + openId, _currentUser, 5, 0, 0);
                        return _currentUser;
                    }
                }
            }

        }


        public ActionResult Index()
        {

            openId = Request["openid"];
            if (string.IsNullOrEmpty(openId))
            {
                return Content("缺少参数");
            }
            // mmtols.Remove(activityUserMemKeyPreFix + openId);
            ViewBag.openId = openId;
            if (CurrentUser != null)
            {
                ViewBag.CurrentUser = CurrentUser;
                if (CurrentUser.QQNumber != null || CurrentUser.phoneHideMid != null) //说明这用户已经绑定了vip
                {
                    return RedirectToAction("NewsShow", new { openId = openId });
                }
            }
            else
            {
                return Content("不存在的用户");
            }
            return View();
        }

        //开通Vip页面
        public ActionResult KaiTong()
        {
            openId = Request["openid"];
            if (string.IsNullOrEmpty(openId))
            {
                return Content("缺少参数");
            }
            if (CurrentUser == null)
            {
                //说明没有获取到用户信息
                return RedirectToAction("Index", new { openId = openId });
            }
            ViewBag.CurrentUser = CurrentUser;
            return View();
        }

        [HttpPost]
        public ActionResult DoKaiTong()
        {
            try
            {
                string qq = Request["qq"];
                string phone = Request["phone"];
                openId = Request["openId"];
                string weixinId = Request["weixinId"];

                UserPhoneBindEntity entity = new UserPhoneBindEntity();
                entity.weixinId = int.Parse(weixinId);
                entity.openId = openId;
                entity.phoneDefEncode = phone;
                entity.phoneHideMid = StringTools.HideMobilePhoneMid4(phone);
                entity.phoneMd5 = StringTools.Md5(phone).ToUpper();
                entity.QQNumber = qq;
                UserPhoneBindBLL bll = new UserPhoneBindBLL();
                int count = bll.Insert(entity);
                //如果开通成功了，更新缓存中的用户数据
                if (count >= 3)
                {
                    CurrentUser.QQNumber = qq;
                    CurrentUser.phoneHideMid = entity.phoneHideMid;
                    mmtols.Add(activityUserMemKeyPreFix + openId, CurrentUser, 5, 0, 0);
                }
                return Content("");
            }
            catch (Exception ex)
            {
                MyTrace.get().add("vip绑定出错:" + ex.Message);
                return Content("绑定错误");
            }

        }

        public ActionResult NewsShow()
        {
            try
            {
                openId = Request["openid"];
                if (string.IsNullOrEmpty(openId))
                {
                    return Content("缺少参数");
                }


                ViewBag.CurrentUser = CurrentUser;

                #region 获取vip资讯数据
                NewsReportEntity entity = null;
                string vipNewsMMKey = StringTools.ChangeRealKey("vipNewsMMKey", "");
                entity = mmtols.Get<NewsReportEntity>(vipNewsMMKey);
                if (entity == null)
                {
                    lock (lockObj)
                    {
                        UserPhoneBindBLL bll = new UserPhoneBindBLL();
                        entity = bll.GetLastVipNewsReport();
                        mmtols.Add(vipNewsMMKey, entity, 24, 0, 0);
                    }
                }
                ViewBag.NewsReport = entity;
                #endregion

                #region  获取盘后推荐股行情
                PanHouTJGBLL pht = new PanHouTJGBLL();
                string phtjgKey = StringTools.ChangeRealKey("PanHouTJG", "");
                string phtjCode = mmtols.Get<string>(phtjgKey);

                if (phtjCode == null)
                {
                    lock (lockObj)
                    {
                        PanHouTJGEntity last = pht.GetLastSet();
                        if (last != null)
                        {
                            phtjCode = last.stockCode;
                            MyTrace.get().add("从数据库中取出盘后推荐股");
                            mmtols.Add(phtjgKey, phtjCode, 365, 0, 0);
                        }
                    }
                }

                if (phtjCode != null)
                {
                    string tempCode = string.Empty;
                    if (phtjCode[0] == '0' || phtjCode[0] == '3')
                    {
                        tempCode = phtjCode.PadLeft(7, '1');
                    }
                    else
                    {
                        tempCode = phtjCode.PadLeft(7, '0');
                    }
                    List<StockPrice> stockPrices = StockRule.GetStockInfoList(tempCode);
                    if (stockPrices != null && stockPrices.Count > 0)
                    {
                        ViewBag.stockPrice = stockPrices[0];
                    }
                }
                #endregion

                #region  获取最新视频
                VideoDataModel vdmodel = null;
                string videoDataKey = StringTools.ChangeRealKey("videoDataKey", System.DateTime.Now.ToString("yyyyMMdd"));
                vdmodel = mmtols.Get<VideoDataModel>(videoDataKey);
                if (vdmodel == null)
                {
                    string json = WebApiHelper.CallGetApi(string.Format(Config.GetVideoDataUrl, System.DateTime.Now.ToString("yyyy-MM-dd")));
                    vdmodel = JsonTools.ToObject<VideoDataModel>(json, DateTimeZoneHandling.Local);
                    mmtols.Add(videoDataKey, vdmodel, 24, 0, 0);
                }
                if (vdmodel != null)
                {
                    //  地区全国 + 版本 >2个+版本中包含机构版 视频读取规则
                    List<Video> resultList = vdmodel.Message.Where(n => n.end_date > System.DateTime.Now && n.ddlarea == "全国" && n.chblist_pro.Contains(",") && n.chblist_pro.Contains("153000000")).OrderBy(n => n.startDate).ToList();
                    ViewBag.VideoList = resultList;
                }
                #endregion


            }
            catch (NullReferenceException ex)
            {
                MyTrace.get().add("VipUserController.NewShows发生错误:" + ex.Message + "  " + ex.Source);
            }
            catch (Exception ex)
            {
                MyTrace.get().add("VipUserController.NewShows发生错误:" + ex.Message);
            }

            return View();
        }

        /// <summary>
        /// 课程预约功能
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult YueYue()
        {
            string url = Request["url"];
            string startTime = Request["startTime"];
            string endTime = Request["endTime"];
            string className = Request["className"];
            openId = Request["openid"];
            string classId = Request["classId"];
            string password = Request["password"];

            ModelMessagesEntity mmsgEntity = new ModelMessagesEntity();
            try
            {
                mmsgEntity.firstText = "您好，你预约的培训课程即将开始";
                mmsgEntity.keyNote1 = className;
                mmsgEntity.keyNote2 = startTime;
                mmsgEntity.keyNote3 = string.Empty;
                mmsgEntity.keyNote4 = string.Empty;
                mmsgEntity.keyNote5 = string.Empty;
                mmsgEntity.keyNote6 = string.Empty;
                mmsgEntity.keyNote7 = string.Empty;
                mmsgEntity.keyNote8 = string.Empty;
                url = url + "?token=" + password + "&nickName=" + openId;
                url = Config.Host_Url2 + "VipUser/WatchViedeoRedirect?goUrl=" + HttpUtility.UrlEncode(url) + "&openid=" + openId + "&className=" + className + "&classId=" + classId;
                mmsgEntity.url = url;
                mmsgEntity.template_id = Config.YuYuemodelId;
                mmsgEntity.topcolor = "#FF0000";
                mmsgEntity.remarkText = "点击直接进入会场等候";
                mmsgEntity.touser = openId;
                mmsgEntity.EarliestTime = DateTime.Parse(startTime).AddMinutes(-10);
                mmsgEntity.weixinId = 8;
                ModelMessagesBLL bll = new ModelMessagesBLL();
                int count = bll.Insert(mmsgEntity);
                if (count > 0)
                {
                    return Content("0");
                }
                else
                {
                    return Content("1");
                }
            }
            catch (Exception ex)
            {
                if (ex.Message.Contains("重复键"))
                {
                    return Content("3");
                }
            }
            return Content("0");

        }

        //观看视频重定向(主要用于会员保存观看视频记录)
        public ActionResult WatchViedeoRedirect()
        {
            openId = Request["openid"];
            string className = Request["className"];
            string classId = Request["classId"];
            string goUrl = Request["goUrl"];
            try
            {
                WatchVideoRecordEntity entity = new WatchVideoRecordEntity();
                entity.openid = openId;
                entity.className = className;
                entity.videoId = int.Parse(classId);
                entity.nickName = "";
                entity.watchTime = System.DateTime.Now;
                entity.weixinId = CurrentUser.weixinUserid;
                WatchVideoRecordBLL bll = new WatchVideoRecordBLL();
                bll.Insert(entity);
            }
            catch (Exception ex)
            {
                MyTrace.get().add("WatchViedeoRedirect 发生错误" + ex.Message);
            }
            return Redirect(HttpUtility.HtmlDecode(goUrl));


        }


    }
}
